package com.dmlll.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dmlll.VO.UserVO;
import com.dmlll.common.DataGridView;
import com.dmlll.common.ResultObj;
import com.dmlll.domain.User;
import com.dmlll.service.UserService;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author dmLll
 * @since 2021-03-31
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Resource
    private UserService userService;

    @RequestMapping("loadUser")
    public DataGridView loadUser(UserVO userVO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("type", 1);
        queryWrapper.eq(userVO.getType() != null && userVO.getType() >= 1, "type", userVO.getType());//不能查询超级管理员
        IPage<User> iPage = userService.page(new Page<User>(userVO.getPage(), userVO.getLimit()), queryWrapper);
        return new DataGridView(iPage.getTotal(), iPage.getRecords());
    }

    @RequestMapping("getUserByAccount")
    public List<User> getUserByAccount(String account) {
        List<User> list = userService.list(new QueryWrapper<User>().eq("acount", account));
        return list;
    }

    @RequestMapping("add")
    public ResultObj add(User user) {
        try {
            if(user.getType()==-1)
                user.setType(1);
            userService.save(user);
        } catch (Exception e) {
            return ResultObj.ADD_ERROR;
        }
        return ResultObj.ADD_SUCCESS;
    }

    @RequestMapping("update")
    public ResultObj update(User user) {
        try {
            if(user.getType()==-1)
                user.setType(1);
            userService.updateById(user);
        } catch (Exception e) {
            return ResultObj.UPDATE_ERROR;
        }
        return ResultObj.UPDATE_SUCCESS;
    }
    @RequestMapping("delete")
    public ResultObj delete(User user){
        try {
            userService.removeById(user.getId());
        } catch (Exception e) {
            return ResultObj.DELETE_ERROR;
        }
        return ResultObj.DELETE_SUCCESS;
    }
}

